//
//  WBGPSPickerViewController.m
//  DingTalkAssistant
//
//  Created by buginux on 2017/7/28.
//  Copyright © 2017年 buginux. All rights reserved.
//

#import "WBGPSPickerViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

static double EARTH_R = 6378137.0;

typedef struct {
    double lat;
    double lng;
}LXLoca;

@interface WBGPSPickerViewController ()<CLLocationManagerDelegate, MKMapViewDelegate>

@property (nonatomic, strong) CLLocationManager *locationmanager;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) UILabel *contentLab;

@end

@implementation WBGPSPickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"GPS 设置";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.contentLab];
    
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    static NSString *ID = @"anno";
    
    MKPinAnnotationView *annoView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annoView == nil) {
        annoView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ID];
        // 显示气泡
        annoView.canShowCallout = YES;
        // 设置绿色
        annoView.pinColor = MKPinAnnotationColorGreen;
    }
    return annoView;
}


#pragma mark MKMapViewDelegate
//地图位置刷新
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    //设置经纬度跨度，越小地图详细
    MKCoordinateSpan  span = MKCoordinateSpanMake(0.01, 0.01);
    //    设置经纬度区域
    MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.coordinate, span);
    //    设置地图显示区域
    [mapView setRegion:region animated:YES];
    
}



-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    
//    NSLog(@"纬度%f,经度%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}

- (MKMapView *)mapView
{
    if (!_mapView) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        CGFloat height = [UIScreen mainScreen].bounds.size.height;

        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,0, width, height-150)];
        //设置用户的跟踪模式
        _mapView.userTrackingMode = MKUserTrackingModeNone;
        //设置标准地图
        _mapView.mapType = MKMapTypeStandard;
        // 不显示罗盘和比例尺
        if (@available(iOS 9.0, *)) {
            _mapView.showsCompass = NO;
            _mapView.showsScale = NO;
        }
        // 开启定位
        _mapView.showsUserLocation = YES;
        _mapView.delegate = self;
        
        UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        [self.mapView addGestureRecognizer:longPressRecognizer];

    }
    return _mapView;
}

- (UILabel *)contentLab{
    if (!_contentLab) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        CGFloat height = [UIScreen mainScreen].bounds.size.height;
        _contentLab = [[UILabel alloc] initWithFrame:CGRectMake(20, height-120, width-40, 100)];
        _contentLab.numberOfLines = 0;
        _contentLab.text = @"位置信息";
        _contentLab.font = [UIFont systemFontOfSize:16.0f];
        _contentLab.textColor = [UIColor lightGrayColor];
        
    }
    return _contentLab;
}

- (void)longPress:(UIGestureRecognizer *)recognizer{
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [recognizer locationInView:self.mapView ];
        CLLocationCoordinate2D touchCoordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView ];
//        NSLog(@"%f %f",touchCoordinate.latitude, touchCoordinate.longitude);
        
        __weak WBGPSPickerViewController *weakSelf = self;
        //设置提示提醒用户打开定位服务
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"设置这个位置" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LXLoca oriLoca = {touchCoordinate.latitude, touchCoordinate.longitude};
            LXLoca loca = [self gcj2wgs:oriLoca];
            [[NSUserDefaults standardUserDefaults] setObject:@(loca.lat) forKey:@"latitude"];
            [[NSUserDefaults standardUserDefaults] setObject:@(loca.lng) forKey:@"longitude"];
               
            NSString *str = [NSString stringWithFormat:@"位置：%f %f",touchCoordinate.latitude, touchCoordinate.longitude];
            weakSelf.contentLab.text = str;
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:okAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

/**
 * wgs2gcj 函数  WGS-84 转 GCJ-02
 */
- (LXLoca)wgs2gcj:(LXLoca)wsgLoca
{
    if ([self isOutOfChinaWithLat:wsgLoca]) {
        return wsgLoca;
    }
    LXLoca loca = [self delta:wsgLoca];
    LXLoca nLoca = {wsgLoca.lat + loca.lat, wsgLoca.lng + loca.lng};
    return nLoca;
}
/**
 * gcj2wgs 函数 GCJ-02 转 WGS-84
 * 这个输出的坐标精度是1米到2米， 如果要更精确的结果，使用 gcj2wgs_exact 函数
 */
- (LXLoca)gcj2wgs:(LXLoca)gcjLoca
{
    if ([self isOutOfChinaWithLat:gcjLoca]) {
        return gcjLoca;
    }
    LXLoca loca = [self delta:gcjLoca];
    LXLoca nLoca = {gcjLoca.lat - loca.lat, gcjLoca.lng - loca.lng};
    return nLoca;
}

- (BOOL)isOutOfChinaWithLat:(LXLoca)loca
{
    if (loca.lng < 72.004 || loca.lng > 137.8347) {
        return true;
    }
    if (loca.lat < 0.8293 || loca.lat > 55.8271) {
        return true;
    }
    
    return false;
}

- (LXLoca)transform:(LXLoca)lxLoca
{
    double xy = lxLoca.lat * lxLoca.lng;
    double absX = sqrt(fabs(lxLoca.lat));
    
    double xPi = lxLoca.lat * M_PI;
    double yPi = lxLoca.lng * M_PI;
    double d = 20.0 * sin(6.0 * xPi) + 20.0 * sin(2.0 * xPi);
    
    double lat = d;
    double lng = d;
    
    lat += 20.0 * sin(yPi) + 40.0 * sin(yPi / 3.0);
    lng += 20.0 * sin(xPi) + 40.0 * sin(xPi / 3.0);
    
    lat += 160.0 * sin(yPi / 12.0) + 320 * sin(yPi / 30.0);
    lng += 150.0 * sin(xPi / 12.0) + 300 * sin(xPi / 30.0);
    
    lat *= 2.0 / 3.0;
    lng *= 2.0 / 3.0;
    
    lat += -100 + 2.0 * lxLoca.lat + 3.0 * lxLoca.lng + 0.2 * lxLoca.lng * lxLoca.lng + 0.1 * xy + 0.2 * absX;
    lng += 300.0 + lxLoca.lat + 2.0 * lxLoca.lng + 0.1 * lxLoca.lat * lxLoca.lat + 0.1 * xy + 0.1 * absX;
    
    LXLoca loca = {lat, lng};
    
    return loca;
}

- (LXLoca )delta:(LXLoca)lxLoca
{
    double ee = 0.00669342162296594323;
    double radLat = lxLoca.lat / 180.0 * M_PI;
    double magic = sin(radLat);
    magic = 1 - ee * magic * magic;
    double sqrtMagic = sqrt(magic);
    LXLoca locaTran = {lxLoca.lng - 105.0, lxLoca.lat - 35.0};
    LXLoca loca = [self transform:locaTran];
    double nlat = (loca.lat * 180.0) / ((EARTH_R * (1 - ee)) / (magic * sqrtMagic) * M_PI);
    double nLng = (loca.lng * 180.0) / (EARTH_R / sqrtMagic * cos(radLat) * M_PI);
    LXLoca nloca = {nlat, nLng};
    return nloca;
}

@end
